package com.sdlh.demo.springboot.common.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * 项目启动 监听主题
 */
@Slf4j
@Component
public class MQTTListener implements ApplicationListener<ContextRefreshedEvent> {

    private final MQTTConnect server;

    @Autowired
    public MQTTListener(MQTTConnect server) {
        this.server = server;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        try {
            server.start();
            server.sub(MQTTConnect.TOPIC,0);
            log.info("-----------消息订阅成功-success----------");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            log.error("-----------消息订阅失败-error-----------");
        }
    }
}
